use anyhow::{Result};
use serde::{Deserialize, Serialize};
use serde_json::json;

use super::{RobotEntity};

pub async fn robots_query_local_robots(token: &String) -> Result<Vec<RobotEntity>> {
    let url = format!("/robot/mysearch");
    //请求的URL
    tracing::debug!("请求的URL:{}", url);
    //获取本机的peer id
    let (peer_id, _) = crate::devices::devices_device_get_peer_id().await?;

    let request_obj = json!({
        "page_size": 1000,
        "page": 1,
        "conditions": {
            "peer_id": peer_id,
        }
    })
    .to_string();
    tracing::debug!("request:{:?}", request_obj);

    let res = crate::request::rrai_cloud_post(&url, token, request_obj).await?;
    //
    let response_obj: RobotSearchResponse = serde_json::from_str(res.as_str())?;
    Ok(response_obj.data)
}

#[derive(Deserialize, Serialize)]
pub struct RobotSearchResponse {
    pub page_size: u32,
    pub page: u32,
    pub total: u32,
    pub data: Vec<RobotEntity>,
}

pub async fn robots_query_by_peer_id(
    token: &String,
    peer_id: &String,
    page_size: u32,
    page: u32,
) -> Result<Vec<RobotEntity>> {
    let url = format!("/robot/mysearch");
    //请求的URL
    tracing::debug!("请求的URL:{}", url);
    let request_obj = json!({
        "page_size": page_size,
        "page": page,
        "conditions": {
            "peer_id": peer_id,
        }
    })
    .to_string();
    tracing::debug!("request:{:?}", request_obj);

    let res = crate::request::rrai_cloud_post(&url, token, request_obj).await?;
    //
    let response_obj: RobotSearchResponse = serde_json::from_str(res.as_str())?;
    Ok(response_obj.data)
}

pub async fn _get_robot_by_id(token: &String, robot_id: u32) -> Result<RobotEntity> {
    //TODO cache

    robots_query_by_id(token, robot_id).await
}

pub async fn robots_query_by_id(token: &String, robot_id: u32) -> Result<RobotEntity> {
    let url = format!("/robot/get/{}", robot_id);

    let res = crate::request::rrai_cloud_get(&url, token).await?;
    tracing::debug!("request:{:?}", res);

    let robot: RobotEntity = serde_json::from_str(res.as_str())?;
    Ok(robot)
}